<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :limit="1"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :http-request="handleUpload"
      :file-list="fileList"
      :class="{disabled:fileList.length>0}"
      :on-change="changeFile"
      :before-upload="beforeUpload"
    >

      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogtupian" :append-to-body="true">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { upload } from '@/api/subject_subject'
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogtupian: false,
      fileList: [

      ],
      isUpload: false
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(value) {
        // console.log(value)    upload/image/2023/03/1678181493692.png
        if (value && !this.isUpload) {
          this.fileList = [
            { name: '',
              url: `http://124.223.14.236:7005/${value}` }
          ]
        }
      }
    }
  },
  methods: {
    beforeUpload(file) {
      // 要开始做文件上传的检查了
      // 文件类型 文件大小
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      // console.log(file.uid)
      // file.uid
      this.currentFileUid = file.uid // 记住当前的uid
      this.showPercent = true
      return true
    },
    changeFile(file, fileList) {
      // console.log(fileList)
      this.fileList = fileList
    },
    // 处理删除
    handleRemove(file, fileList) {
      // console.log(file, fileList)
      this.fileList = fileList
      if (fileList.length === 0) {
        this.$emit('input', '')
      }
    },
    // y预览
    handlePictureCardPreview(file) {
      console.log(file)
      // this.dialogImageUrl = `http://124.223.14.236:7005/${file.url}`
      this.dialogImageUrl = file.url
      console.log(this.dialogImageUrl)
      this.dialogtupian = true
    },
    async handleUpload({ file }) {
      // console.log({ file })
      // 异步文件上传
      // 1、实例化FormData
      const fd = new FormData()
      // // 2、fd中追加文件
      fd.append('file', file)
      // // 3、调用接口
      const res = await upload(fd)
      // console.log(res.data.url)// upload/images/20230221/1676963826885.png
      this.isUpload = true
      this.$emit('input', res.data.url)
    }
  }
}
</script>

<style>
.disabled .el-upload--picture-card{
  display: none;
}
</style>
